<?php
// +----------------------------------------------------------------------
// | 食得鲜
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.shidexian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 何锐 <poptser@foxmail.com>  [ ON THE WAY ]
// +----------------------------------------------------------------------
// | DateTime：2017-06-20 15:37:55
// +----------------------------------------------------------------------

namespace SDXApi\Controller;
use Think\Controller;
use Think\Log;
/**
 * 订单处理
 * @author  何锐 <poptser@foxmail.com>  [ ON THE WAY ]
 */
class BscController extends Controller{

    protected $store_id = 0;
    protected $store_user_id = 0;
    protected $data = array();
    protected $server_url = "";
    protected $client_store_no = '';
    protected $app_secret = "";
    protected $app_key = "";

    protected function _initialize() {
        if(PLATFORM_TYPE=="formal"){
            //正式服务器
            $this->server_url = "http://bsc.3send.cn/index.php?g=Open&m=Order&a=";
            $this->client_store_no = '4143621805';
            $this->app_secret = "FFrKCmdMItGaIvtfsElgJse54q4A2PGe";
            $this->app_key = "kk3CxeQ4";
            $data['scc_id'] = 2;    //此单取货点ID
        }else{
            //测试服务器
            $this->server_url = "http://bsc.test.shidexian.com/index.php?g=Open&m=Order&a=";
            $this->client_store_no = '3627666048';
            $this->app_secret = "BOFQHe3WtMZApMOdoKNImA5OSSI5lmSi";
            $this->app_key = "7JJHfULp";
            $data['scc_id'] = 4;    //此单取货点ID
        }




        $client_time = time();
        $client_sign_method = "sha1";
        $old_sign = $this->client_store_no.$client_time.$client_sign_method.$this->app_secret.substr($client_time, -1);;
        $data['sign'] = strtoupper(sha1($old_sign));
        $data['time'] = $client_time;
        $data['store_no'] = $this->client_store_no;
        $data['sign_method'] = $client_sign_method;
        $data['app_key'] = $this->app_key;

        $this->data = $data;
    }

    /**
     * 推送订单
     * @param null $order_id
     * @return bool
     */
    public function post_order($order_id=null){
        //$order_id = 545331;
        if(empty($order_id)){
            return false;
        }
        $data = $this->data;
        $order_info = M("order_info")
            ->field("order_sn,consignee,mobile,province,city,district,address,longitude,latitude,sign_building,best_time_start,best_time,postscript,address_name,wid")
            ->where(array("order_id"=>$order_id))->find();

        //获取取货点配置信息
        $pickup_point_list = C('BSC_CONFIG');
        $pickup_point_info = $pickup_point_list[$order_info['wid']];
        //设置取货点id
        $data['scc_id'] = $pickup_point_info['scc_id'];

        $data['third_sn'] = $order_info['order_sn'];    //订单号
        $data['consignee'] = $order_info['consignee'];   //收货人姓名
        $data['mobile'] = $order_info['mobile'];      //手机号
        $data['province'] = M('region')->where(array('region_id'=>$order_info['province']))->getField('region_name');    //省份
        $data['city'] = M('region')->where(array('region_id'=>$order_info['city']))->getField('region_name');        //城市
        $data['district'] = M('region')->where(array('region_id'=>$order_info['district']))->getField('region_name');    //区县
        $data['address'] = $order_info['address'].$order_info['address_name'];     //详细地址

        if($order_info['longitude']>$order_info['latitude']){
            $data_gps =GCJ02_To_BD09($order_info['longitude'],$order_info['latitude']);
            $longitude = $data_gps['latitude'];
            $latitude = $data_gps['longitude'];
        }else{
            $data_gps =GCJ02_To_BD09($order_info['latitude'],$order_info['longitude']);
            $longitude = $data_gps['latitude'];
            $latitude = $data_gps['longitude'];
        }


        $data['longitude'] = $longitude;   //经度
        $data['latitude'] = $latitude;    //纬度

        $data['landmarks'] = $order_info['sign_building'];   //地标
        $data['delivery_start_time'] = $order_info['best_time_start']; //开始配送时间
        $data['delivery_end_time'] = $order_info['best_time'];   //结束配送时间
        $data['remark'] = $order_info['postscript'];   //订单备注

        $goods_list = $this->get_goods_list_real($order_id);

        //订单商品数量
        $order_bag = S('order_bag_'.$order_id);
        if(!empty($order_bag)){
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['goods_name'] =$type_name.$order_item['current'];
                $tmp_order_item['goods_price'] =0;
                $tmp_order_item['goods_sn'] =$order_info['order_sn'].str_pad($order_item['all'],2,"0",STR_PAD_LEFT).str_pad($order_item['current'],2,"0",STR_PAD_LEFT).$order_item['type'];
                $tmp_order_item['goods_number'] =1;
                $tmp_order_item['goods_weight'] =1;
                $order_goods[] = $tmp_order_item;
            }
            $order_weight = 0;
            foreach ($goods_list as $key=>$value){
                $order_weight += $value['goods_weight']*$value['goods_number'];
            }

            $data['order_weight'] = $order_weight;   //订单重量指定
            $data['goods_num'] = count($order_goods);    //订单商品袋数

            $data['goods'] = json_encode($order_goods);
        }else{
            $data['goods'] = json_encode($goods_list);
        }


        $post_value = http_post($this->server_url."post_order",$data);
        //echo $post_value;
        $post_value_array = json_decode($post_value, true);               //JSON 编码
        if($post_value_array['status']==1){
            //成功推送至BSC
            M("order_info")->where(array("order_id"=>$order_id))->setField("push_bsc",1);
            $this->write_log($order_info['order_sn'],'bsc_ok');
            return true;
        }else{
            //推送至BSC失败
            $this->write_log($order_info['order_sn']." CODE:".$post_value_array['err_code']." msg:".$post_value_array['error_msg'],'bsc_fail');
            return $order_info['order_sn'].":".$post_value_array['error_msg'].$data_gps['latitude'].$data_gps['longitude'];
        }
    }

    private function get_bag_type_name($type){
        $name = "";
        switch ($type){
            case "1":
                $name="藏";
                break;
            case "2":
                $name="冻";
                break;
            case "0":
                $name="常";
                break;
        }
        return $name;
    }
//* @param $contact
//* @param $phone
//* @param $store_id
//* @param $third_sn
//* @param $op_type 1:[开始配送] 2:[完成配送] 3:[已到站] 4:[需回仓]
//                  5:[延迟订单] 6:[配送订单] 7:[问题单] 8 司机揽件
//                  9返回揽件 10反仓确认 11周边撤单  12取消回仓
//* @param $time
//* @param $text
//* @param $best_time
    /**
     *订单状态回调
     *
     *order_sn contact phone op_time remark
     */
    public function order_notify(){
        $data_json = str_replace('&quot;','"',I("post.data"));
        $this->write_log($data_json,'bsc_order_notify');

        $notify = json_decode($data_json, true);

        $sign =strtoupper(md5($this->app_secret.$this->app_key.$this->client_store_no.$notify['order_sn'].$notify['op_type'].$notify['op_time'].substr($notify['op_time'], -1)));
        if($sign==$notify['sign']){
            switch($_SERVER['SERVER_NAME']){
                case 'api.xian3.com':
                    $this_url='xian3.com';
                    break;
                case 'api.test.shidexian.com':
                    $this_url='test.shidexian.com';
                    break;
                case 'api.shidexian.com':
                    $this_url='w.shidexian.com';
                    break;
                default:
                    $this_url='w.shidexian.com';
                    break;
            }

            $list = M("order_info")->where(array("order_sn"=>$notify['order_sn']))
                ->field("wid,pay_status,shipping_status,order_status,
                surplus,money_paid,order_amount,best_time_start,
                best_time,consignee,order_sn,mobile,user_id,order_id")->find();
            if(empty($list)){
                $this->write_log("未找到此订单号：".$notify['order_sn'],'order_notify');
                return false;
            }

            $wechat_param=array();
            switch ($notify['op_type']){
                case 1:
                    //开始配送
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=1;
                    $data_save['shipping_time']=gmtime();
                    $data_save['wp_userid'] = 99999;
                    $data_save['station'] = 2; //开始配送 修改到站状态为已出站
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,1,$list['pay_status'],"开始配送",1);
                        $this->record_logistics($list['order_id'],1,"订单已由:".$notify['contact']."「 ".$notify['phone']." 」开始配送");
                    }
                    $datetime = date("Y-m-d",$list['best_time_start']);
                    $remark['best_time'] = $datetime.' '.date("H:i:s",$list['best_time_start']).'-'.date("H:i:s",$list['best_time']);
                    $oid=$list['user_id'];
                    $Code=md5($oid.'sdx@9999');
                    $goods_name=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->limit(1)->getField("goods_name");
                    $goods_number=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->count();
                    $wechat_param['url']="https://".$this_url."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHshipping_start_notice";
                    $wechat_param['first']='尊敬的'.$list['consignee'].'，您所订购的'.$goods_name.'等'.$goods_number.'件商品已经在配送中，预计到达时间为'.$remark['best_time'].'，请保持手机畅通。';
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=$notify['contact'];
                    $wechat_param['keyword3']=$notify['phone'];
                    $wechat_param['remark']=array("您的订单收货码为：[ ".$remark['code']." ],确认收货时请将此码提供给配送员。如代收，请把该码提供给代收人","#FF0000");
                    A("Smsapi")->send_message_api('receipt_verification',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$remark,'',$wechat_param);

                    break;
                case 2:

                    //处理库存
                    $is_shipping_status = M("order_action")->where(array("order_id"=>$list['order_id'],"shipping_status"=>2))->count();
                    if(empty($is_shipping_status)){
                        $this->order_buckle_inventory($list);
                        $dk_msg = " 处理库存";
                    }else{
                        $dk_msg = " 未处理库存";
                    }

                    //完成配送
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=2;
                    $data_save['confirm_time']=gmtime();
                    $data_save['wp_userid']=99999;
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,2,$list['pay_status'],"配送完成".$dk_msg,1);
                        $this->record_logistics($list['order_id'],2,"配送完成");
                    }

                    $oid=$list['user_id'];
                    $Code=md5($oid.'sdx@9999');
                    $goods_name=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->limit(1)->getField("goods_name");
                    $goods_number=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->count();
                    $louxiaoer_info=A("Smsapi")->get_louxiaoer_info($list['order_id']);
                    if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                        $housekeeper="微信添加楼管家".$louxiaoer_info['name']."-".$louxiaoer_info['phone']."还能最高返8元。祝生活愉快！";
                    }else{
                        $housekeeper="联系楼管家还能再返现。如需添加，请于微信公众号留言。";
                    }
                    $wechat_param['url']="https://".$this_url."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHorder_finish";
                    $wechat_param['first']='尊敬的'.$list['consignee'].',您所订购的'.$goods_name.'等'.$goods_number.'件商品已经成功送达';
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=sprintf("%.2f",($list['order_amount']+$list['money_paid']+$list['surplus']));
                    $wechat_param['keyword3']=date("Y-m-d H:i:s");
                    $wechat_param['remark']=$housekeeper;
                    A("Smsapi")->send_message_api('order_finish',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],array(),'',$wechat_param);
                    //确认收货，赠送红包
                    D('Userbonus')->send_bonus_to_user($list['user_id'],$list['order_id']);
                    break;
                case 3:
                    //已到站
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"已到达物流点",1);
                    break;
                case 4:
                    //需回仓
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 3;
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"需回仓//".$notify['text'],1);
                    }
                    break;
                case 5:
                    //延迟订单
                    $shipping_arrive_time = explode(',', $notify['best_time']);
                    $data_save['best_time_start'] = $shipping_arrive_time[0];
                    $data_save['best_time'] = $shipping_arrive_time[1];

                    //$diff_time = round(($data_save['best_time_start']-$list['best_time_start'])/3600/24);

                        $data_save['order_status']=5;
                        $data_save['shipping_status']=5;
                        $data_save['wp_userid'] = 0;
                        $huic_test ="";



                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"延迟订单//".$notify['remark'].$huic_test,1);
                    }
                    $best_time = explode(",",$notify['best_time']);
                    $datetime = date("Y-m-d",$best_time[0]);
                    $smsremark['best_time'] = $datetime.' '.date("H:i:s",$best_time[0]).'-'.date("H:i:s",$best_time[1]);
                    $smsremark['action'] = $notify['text'].$huic_test;

                    $code=md5($list['user_id'].'sdx@9999');
                    $wechat_param=array();
                    $wechat_param['url']='https://'.$this_url.'/?index&sid='.$list['user_id'].'&code='.$code.'&lll=#!/reted?ordId='.$list['order_sn'];
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=$notify['text'];
                    $wechat_param['keyword3']="[".date('Y-m-d H:i:s',$list['best_time_start'])."] - [".date('Y-m-d H:i:s',$list['best_time'])."]";
                    $wechat_param['keyword4']="[".date('Y-m-d H:i:s',$best_time[0])."] - [".date('Y-m-d H:i:s',$best_time[1])."]";
                    A("Smsapi")->send_message_api('delayed_order',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$smsremark,null,$wechat_param);
                    break;
                case 6:
                    //配送退单
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;

                    M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);

                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"配送员退单",1);
                    break;
                case 7:
                    //问题订单
                    $shipping_arrive_time = explode('-', $notify['best_time']);
                    $data_save['best_time_start'] = $shipping_arrive_time[0];
                    $data_save['best_time'] = $shipping_arrive_time[1];


                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 1;
                    $data_save['action_type'] = 6; //问题单日志

                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"问题订单//".$notify['remark'],1);
                    }
                    $datetime = date("Y-m-d",$data_save['best_time_start']);
                    $smsremark['best_time'] = $datetime.' '.date("H:i:s",$data_save['best_time_start']).'-'.date("H:i:s",$data_save['best_time']);
                    $smsremark['action'] = " [ ".$notify['text']." ] ";
                    A("Smsapi")->send_message_api('question_order',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$smsremark);

                    break;
                case 8:
                    //司机派送揽件
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"司机派送揽件",1);
                    $this->record_logistics($list['order_id'],5,"司机派送揽件");
                    break;
                case 9:
                    //司机回仓揽件
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"司机回仓揽件",1);
                    break;
                case 10:
                    //司机回仓确认
                    //改订单为需回仓
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"司机回仓确认",1);
                    $data_save['outgo'] = 2;
                    M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    break;
                case 11:
                    //周边撤单
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 1;

                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"周边撤单",1);
                    }
                    break;
                case 12:
                    //取消回仓
                    $data_save['outgo'] = 1;             //已出仓
                    $data_save['station'] = 1;           //已回仓
                    $data_save['shipping_status'] = 5;   //配货完成
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"取消回仓",1);
                    }
                    break;
                default:
                    $this->write_log("未找到此方式：".$notify['op_type'],'order_notify');
            }
        }else{
            $this->write_log("校验失败:".$data_json."///".$notify['sign'],'order_notify');
        }
        echo "success";

    }
    /**
     * 写入订单物流信息
     * @param $order_id
     * @param $shipping_status
     * @param $remark
     */
    public function record_logistics($order_id, $shipping_status, $remark){
        $data['log_time']=gmtime();
        $data['remark']=$remark;
        $data['shipping_status']=$shipping_status;
        $data['order_id']=$order_id;
        M('logistics')->add($data);
    }

    /**
     * 订单操作记录
     * @param $user         //操作人描述
     * @param $id           //订单ID
     * @param $order        //订单状态
     * @param $shipping     //配送状态
     * @param $pay          //支付状态
     * @param $note         //操作备注
     * @param $to_user         //1 显示到用户
     */
    public function write_order_action($user, $id, $order, $shipping, $pay, $note,$to_user=0){
        $data['action_user']=$user;
        $data['order_id']=$id;
        $data['order_status']=$order;
        $data['shipping_status']=$shipping;
        $data['pay_status']=$pay;
        $data['action_note']=$note;
        $data['log_time']=gmtime();
        $data['user_id']=1;
        $data['to_user']=$to_user;
        M('order_action')->add($data);
    }

    public function write_log($message,$filename){
        $log = new Log();
        $destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';

        $log->write($message,'DEBUG','',$destination);
    }

    /**
     * 获取订单状态
     * @param null $order_sn
     * @return bool
     */
    public function get_order_action($order_sn=null){
        $order_sn = 2017062615050964447;
        if(empty($order_sn)){
            return false;
        }
        $data = $this->data;
        $data['third_sn'] = $order_sn;
        $post_value = http_post($this->server_url."select_order_status",$data);
        $post_value_array = json_decode($post_value, true);               //JSON 编码
        //dump($post_value_array);
    }

    /**
     * TODO 获取订单内剩余商品数
     * rui
     * @param $order_id
     * @param $no_gift
     * @return mixed
     */
    public function get_goods_list_real($order_id,$no_gift =  false){
        $buy_goods_list = $this->get_goods_list_by_order($order_id,$no_gift);

        $refund_goods_list = $this->get_refund_goods_list($order_id);

        foreach ($buy_goods_list as $key=>$value){
            $edit_goods = true;
            foreach ($refund_goods_list as $key2=>$value2){
                if($value['rec_id']==$value2['order_goods_id']){
                    $buy_goods_list[$key]['goods_number'] = $value['goods_number']-$value2['refund_number'];
                    $edit_goods = false;
                }
            }
            if($edit_goods){
                $buy_goods_list[$key]['goods_number'] = $value['goods_number'];
            }
            $buy_goods_list[$key]['goods_weight'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField("goods_weight");
            if($buy_goods_list[$key]['goods_number']==0){
                unset($buy_goods_list[$key]);
            }
        }
        return $buy_goods_list;
    }

    /**
     * 根据订单ID获取订单里面的原始商品（未退款之前的）
     * rui
     * @param $order_id
     * @return mixed
     */
    private function get_goods_list_by_order($order_id,$no_gift=false){
        if($no_gift){
            $where['order_id'] = $order_id;
            $where['giving'] = array("neq",1);
            return M("order_goods")->field("rec_id,goods_id,goods_name,goods_sn,goods_number,goods_price")->where($where)->select();
        }else{
            return M("order_goods")->field("rec_id,goods_id,goods_name,goods_sn,goods_number,goods_price")->where(array("order_id"=>$order_id))->select();
        }

    }

    /**
     * 查询订单的退款商品记录
     * rui
     * @param $order_id
     * @return mixed
     */
    private function get_refund_goods_list($order_id){
        $refund_detail = M("refund_detail")->field("order_goods_id,sum(refund_number) as refund_number ,sum(surplus_number) as surplus_number,goods_id,goods_name,goods_sn ")->where(array("order_id"=>$order_id))->group('order_goods_id')->select();
        return $refund_detail;
    }


    /*
 * TODO 收货确认减冻结库存
 * */
    private function order_buckle_inventory($order){
        $wid=$order['wid'];
        $where='(order_id='.$order['order_id'].' and is_presell=0) or (order_id='.$order['order_id'].' and is_presell=1 and buckle_inventory=1)';
        $order_goods=M('order_goods')->where($where)->select();
        if($order_goods){
            $goodsstorage_mod=D('Goodsstorage');
            $goodsfreezerecord=D('Goodsfreezerecord');
            $refund_detail=M('refund_detail');
            $rdgoods=array();
            //检查退货退款时是否已经减掉了冻结库存，若有，该操作则不进行减操作
            $rdlist=$refund_detail->field('goods_id,SUM(refund_number) as refund_number')
                ->where(array('order_id'=>$order['order_id']))
                ->group('goods_id')
                ->select();
            if($rdlist){
                foreach ($rdlist as $key=>$val){
                    $rdgoods[$val['goods_id']]=$val['refund_number'];
                }
            }
            foreach ($order_goods as $k=>$v){
                $gsdata=$goodsstorage_mod->get_warehous_goods($wid,$v['goods_id']);
                if($gsdata){
                    if(!empty($rdgoods[$v['goods_id']])){
                        $refund_number=$rdgoods[$v['goods_id']];
                        $v['goods_number']=$v['goods_number']-ceil($refund_number);
                    }
                    if($v['goods_number']==0){// 过滤订单商品购买数据为0时，不插入冻结库存记录
                        continue;
                    }
                    //减去冻结库存
                    $goodsstorage_mod->save_freeze_theactual_goods($wid,$v['goods_id'],$v['goods_number']);
                    $goodsfreezerecorddata=array(
                        'goods_storage_id'=>$gsdata['id'],
                        'wid'=>$wid,
                        'goods_id'=>$v['goods_id'],
                        'goods_sn'=>$v['goods_sn'],
                        'goods_name'=>$v['goods_name'],
                        'freeze_num'=>$v['goods_number'],
                        'real_num'=>0,
                        'frozen_num'=>$gsdata['freeze_num']-$v['goods_number'],
                        'defective_num'=>0,
                        'operation_userid'=>0,
                        'average_userid'=>$order['user_id'],
                        'operation_addtime'=>gmtime(),
                        'source_no'=>$order['order_sn'],
                        'record_type'=>6,
                        'remark'=>'确认收货',
                    );
                    //生成冻结库存记录
                    $goodsfreezerecord->add_freeze_record($goodsfreezerecorddata);
                }else{
                    continue;
                }
            }
        }else{
            return false;
        }
    }


    public function test(){

        $data_json = '{"order_sn":"2017090521114934958","contact":"\u9648\u660e\u4eae","phone":"17688460220","op_time":1504752545,"op_type":2,"sign":"2D2C510E7FFEFE87DAA67D0AC29CF1D7","remark":null,"best_time":null}';

        $notify = json_decode($data_json, true);


            $list = M("order_info")->where(array("order_sn"=>$notify['order_sn']))
                ->field("wid,pay_status,shipping_status,order_status,
                surplus,money_paid,order_amount,best_time_start,
                best_time,consignee,order_sn,mobile,user_id,order_id")->find();
            if(empty($list)){
                exit("未找到此订单号");
            }
            switch ($notify['op_type']){
                case 1:
                    //开始配送
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=1;
                    $data_save['shipping_time']=gmtime();
                    $data_save['wp_userid'] = 99999;
                    $data_save['station'] = 2; //开始配送 修改到站状态为已出站
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,1,$list['pay_status'],"开始配送");
                    }
                    break;
                case 2:
                    //完成配送
                    //$this->order_buckle_inventory($list);

                    //处理库存

                    break;
                case 3:
                    //已到站
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"已到达物流点");
                    break;
                case 4:
                    //需回仓
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 3;
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"需回仓//".$notify['text']);
                    }
                    break;
                case 5:
                    //延迟订单
                    $shipping_arrive_time = explode(',', $notify['best_time']);
                    $data_save['best_time_start'] = $shipping_arrive_time[0];
                    $data_save['best_time'] = $shipping_arrive_time[1];

                    //$diff_time = round(($data_save['best_time_start']-$list['best_time_start'])/3600/24);

                    $data_save['order_status']=5;
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $huic_test ="";



                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"延迟订单//".$notify['remark'].$huic_test);
                    }
                    break;
                case 6:
                    //配送退单
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;

                    M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);

                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"配送员退单");
                    break;
                case 7:
                    //问题订单
                    $shipping_arrive_time = explode('-', $notify['best_time']);
                    $data_save['best_time_start'] = $shipping_arrive_time[0];
                    $data_save['best_time'] = $shipping_arrive_time[1];


                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 1;
                    $data_save['action_type'] = 6; //问题单日志

                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"问题订单//".$notify['remark']);
                    }
                    break;
                case 8:
                    //司机派送揽件
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"司机派送揽件");
                    break;
                case 9:
                    //司机回仓揽件
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"司机回仓揽件");
                    break;
                case 10:
                    //司机回仓确认
                    //改订单为需回仓
                    $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"司机回仓确认");
                    $data_save['outgo'] = 2;
                    M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    break;
                case 11:
                    //周边撤单
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 1;

                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"周边撤单");
                    }
                    break;
                default:
                    exit("未找到此方式");
            }
        echo "success";

    }
}